package com.boco.modules.fdoc.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.boco.modules.fdoc.dao.UserDao;
import com.boco.modules.fdoc.dao.UserRelationsDao;
import com.boco.modules.fdoc.model.UserEntity;
import com.boco.modules.fdoc.model.UserRelationsEntity;
import com.boco.modules.fdoc.service.UserRelationsService;

@Service
public class UserRelationServiceImpl implements UserRelationsService{
	@Resource
	UserRelationsDao userRelationsDao;
	
	@Resource
	UserDao userDao;
	
	@Override
	public int insert(UserRelationsEntity userRelationsEntity) {
		UserEntity user = userDao.get(userRelationsEntity.getUid());
		if (user != null) {
			String userName = user.getRealName();
			//从user对象中获取uid为当前值的userName,放入userRelations对象
			userRelationsEntity.setUserName(userName);
		}
		UserEntity mainUserEntity = userDao.getByRelations(userRelationsEntity.getIdCard());
		// 设置户主：若之前有其他用户添加过这位家庭成员，则户主仍为第一次添加的用户
		if (mainUserEntity != null) {
			userRelationsEntity.setMainUserUid(mainUserEntity.getUid());
		}else {   //若之前无其他用户添加这位家庭成员，则户主为当前用户
			userRelationsEntity.setMainUserUid(userRelationsEntity.getUid());
		}
		Date createDate = new Date();
		userRelationsEntity.setCreateTime(createDate);
		userRelationsEntity.setUpdateTime(createDate);
		userRelationsDao.insert(userRelationsEntity);
		return userRelationsEntity.getId();
	}

	@Override
	public int update(UserRelationsEntity userRelationsEntity) {
		UserEntity user = userDao.get(userRelationsEntity.getUid());
		if (user != null) {
			String userName = userDao.get(userRelationsEntity.getUid()).getRealName();
			//从user对象中获取uid为当前值的userName,放入userRelations对象
			userRelationsEntity.setUserName(userName);
		}
		Date updateDate = new Date();
		userRelationsEntity.setUpdateTime(updateDate);
		return userRelationsDao.update(userRelationsEntity);
	}

	@Override
	public int delete(UserRelationsEntity userRelationsEntity) {
		return userRelationsDao.delete(userRelationsEntity);
	}

	@Override
	public List<UserRelationsEntity> getByUid(String uid) {
		return userRelationsDao.getByUid(uid);
	}

}
